import { Form, Input, Button } from 'antd';
import { loginDataType } from '../interface'
import { apiLogin } from '../api'
import Cookie from 'js-cookie'

const Login = () => {


    // 验证成功的回调函数
    const onFinish = (data: loginDataType) => {
        apiLogin(data).then((res:any) => {
            // 将token保存到cookie中
            Cookie.set('token', res.token);


            // 跳转页面
            window.location.href = '/'
        })
     }

    return <div>
        <Form
            name="basic"
            onFinish={onFinish} // 校验成功的回调函数
            autoComplete="off"
        >
            <Form.Item
                label="用户名"
                name="username"
                rules={[
                    // 非空校验
                    { required: true, message: 'Please input your username!' },
                    // 自定义校验
                    {
                        // rule:当前formItem的实例
                        // 当前表单的内容
                        validator(rule, value) {
                            const reg = /^[0-9][a-z]{4,6}$/
                            if(reg.test(value) || !value) {
                                // 校验成功
                                return Promise.resolve()
                            } else {
                                // 校验失败
                                return Promise.reject()
                            } 
                        },
                        message: '您输入的内容不合法'
                    }
                ]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: 'Please input your password!' }]}
            >
                <Input.Password />
            </Form.Item>

            <Form.Item >
                <Button type="primary" htmlType="submit">
                    登录
                </Button>
            </Form.Item>
        </Form>
    </div>
}

export default Login